<template>
  <div class="sidebar-container" @click="handleSidebarClick">
    <!-- 顶部头像和用户名区域 -->
    <div class="user-info">
      <div class="avatar-wrap">
        <img 
          :src="avatarUrl" 
          alt="用户头像" 
          class="avatar"
          @error="handleAvatarError"
        >
      </div>
      <div class="username">{{ userName }}</div> 
    </div>
    
    <!-- 功能导航区 -->
    <div class="nav-list">
      <template v-for="(item, index) in navItems" :key="index">
        <!-- 普通导航项 -->
        <button 
          v-if="item.type !== 'settings'"
          class="nav-item"
          @click="handleNavClick(item, $event)"  
        >
          <i :class="item.icon"></i>
          <!-- 通讯录图标小红点 -->
          <span 
            v-if="item.type === 'contacts' && unreadFriendRequests > 0" 
            class="unread-badge"
          >
            {{ unreadFriendRequests }}
          </span>
        </button>
        
        <!-- 设置按钮及其下拉菜单 -->
        <div v-else class="settings-container">
          <button 
            class="nav-item"
            @click="handleSettingsClick($event)"  
            ref="settingsButton"
          >
            <i :class="item.icon"></i>
          </button>
          
          <!-- 下拉菜单 -->
          <div 
            class="settings-menu" 
            v-if="showSettingsMenu" 
            ref="settingsMenu"
            @click.stop
          >
            <button class="menu-item" @click="handleLogout">退出登录</button>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup>
import { ref, defineEmits, onMounted, onUnmounted } from 'vue';
import { parseToken } from '../utils/jwt';

// 接收未读好友请求数量
const props = defineProps({
  unreadFriendRequests: {
    type: Number,
    default: 0
  }
});

// 定义事件
const emit = defineEmits(['nav-click', 'logout']);

// 状态管理
const avatarUrl = ref('');
const userName = ref('');
const showSettingsMenu = ref(false); // 控制设置下拉菜单显示

// 引用元素
const settingsButton = ref(null);
const settingsMenu = ref(null);

// 导航菜单项
const navItems = ref([
  { icon: 'fa fa-commenting', type: 'chats' },   // 1. 消息
  { icon: 'fa fa-address-book', type: 'contacts' },   // 2. 联系人
//  { icon: 'fa fa-folder', type: 'files' },        // 3. 文件
  { icon: 'fa fa-butterfly', type: 'butterfly' },  // 4. 自定义功能
  { icon: 'fa fa-cog', type: 'settings' },        // 5. 设置
//  { icon: 'fa fa-bolt', type: 'tools' },           // 6. 工具
  { icon: 'fa fa-music', type: 'music' },          // 7. 音乐
 // { icon: 'fa fa-book', type: 'books' },           // 8. 书籍
]);

// 处理侧边栏点击（除了设置按钮外的区域）
const handleSidebarClick = () => {
  showSettingsMenu.value = false;
};

// 处理普通导航项点击
const handleNavClick = (item, event) => {
  // 阻止事件冒泡，确保先处理导航逻辑
  event.stopPropagation();
  showSettingsMenu.value = false;
  emit('nav-click', item.type);
};

// 处理设置按钮点击
const handleSettingsClick = (event) => {
  // 阻止事件冒泡到侧边栏和document
  event.stopPropagation();
  showSettingsMenu.value = !showSettingsMenu.value;
};

// 退出登录方法
const handleLogout = () => {
  showSettingsMenu.value = false;
  emit('logout');
};

// 全局点击处理 - 处理侧边栏外部的点击
const handleDocumentClick = () => {
  showSettingsMenu.value = false;
};

// 组件挂载时
onMounted(() => {
  // 初始化用户信息
  try {
    const token = localStorage.getItem('token');
    const userInfoStorage = JSON.parse(localStorage.getItem('user_info') || '{}');
    const parsed = parseToken(token);
    
    avatarUrl.value = userInfoStorage.avatarUrl || '/images/avatar-self.png';
    userName.value = parsed.userName || userInfoStorage.userName || '用户';
  } catch (error) {
    console.error('Error loading user info:', error);
    avatarUrl.value = '/images/avatar-self.png';
    userName.value = '未知用户';
  }
  
  // 添加全局文档点击监听
  document.addEventListener('click', handleDocumentClick);
});

// 组件卸载时
onUnmounted(() => {
  // 移除全局事件监听
  document.removeEventListener('click', handleDocumentClick);
});

// 头像加载失败处理
const handleAvatarError = () => {
  avatarUrl.value = '/images/avatar-self.png';
};
</script>

<style scoped>
.sidebar-container {
  width: 60px;
  background-color: rgba(64, 62, 62, 0.6);
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 16px;
  box-sizing: border-box;
}

/* 用户信息区域 */
.user-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 16px;
}

.avatar-wrap {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-bottom: 8px;
  overflow: hidden;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.username {
  color: #ccc;
  font-size: 10px;
  white-space: nowrap;
}

/* 导航列表 */
.nav-list {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  flex: 1;
}

.nav-item {
  width: 40px;
  height: 40px;
  background-color: transparent;
  border: none;
  color: #ccc;
  font-size: 18px;
  margin-bottom: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: background-color 0.2s ease;
  position: relative;
}

.nav-item:hover {
  background-color: #444;
}

/* 未读小红点样式 */
.unread-badge {
  position: absolute;
  top: -2px;
  right: -2px;
  background-color: #ff0000;
  color: white;
  font-size: 10px;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 设置按钮容器 */
.settings-container {
  position: relative;
}

/* 下拉菜单样式 */
.settings-menu {
  position: absolute;
  left: 100%;
  top: 50%;
  transform: translateY(-50%);
  margin-left: 8px;
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15);
  width: 120px;
  z-index: 1000;
  animation: fadeIn 0.2s ease-in-out;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translate(-10px, -50%);
  }
  to {
    opacity: 1;
    transform: translate(0, -50%);
  }
}

/* 菜单项样式 */
.menu-item {
  width: 100%;
  padding: 8px 12px;
  text-align: left;
  background: none;
  border: none;
  cursor: pointer;
  transition: background-color 0.2s;
}

.menu-item:hover {
  background-color: #f0f0f0;
}
</style>
